<?php

class Application_Plugin_Access_Plugin extends Nimblecms_Controller_Plugin {
	
	private $_noAuth = array(
		'module' => 'default',
		'controller' => 'auth',
		'action' => 'login'
	);
	private $_noAcl = array(
		'module' => 'default',
		'controller' => 'auth',
		'action' => 'login'
	);
	
	public function __construct() {
		parent::__construct();
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		
		$auth = Zend_Auth::getInstance();
		
		$acl = Nimblecms_Acl::getInstance()->getAcl();
		
		$userModel = Doctrine_Core::getTable('Users_Model_Users');
		
		if($auth->hasIdentity()) {
			$user = $userModel->find((int)$auth->getIdentity()->id);
			$user->last_ip = $request->getClientIp();
			$user->last_enter = time();
			$user->save();
			$role = $user->role;
		} else {
			$role = 'guest';
		}
		
		$module = $request->module;
		$controller = $request->controller;
		$action = $request->action;
		
		$resource = $module . '_' . $controller;
		
		if (!$acl->has($resource)) {
			$resource = null;
		}
		
		if (!$acl->isAllowed($role, $resource, $action)) {
			if (!$auth->hasIdentity()) {
				$module     = $this->_noAuth['module'];
				$controller = $this->_noAuth['controller'];
				$action     = $this->_noAuth['action'];
			} else {
				$module     = $this->_noAcl['module'];
				$controller = $this->_noAcl['controller'];
				$action     = $this->_noAcl['action'];
			}
		}
		$request -> setModuleName($module)
				 -> setControllerName($controller)
				 -> setActionName($action);
	}
}

?>